// components/search/search.js
import { http } from '../../utils/request'
import { showToast } from '../../utils/show_toast'
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    bgColor: {
      type: String,
      value: '#1989fa'
    },
    shape: {
      type: String,
      value: 'round'
    },
    isTop: {
      type: Boolean,
      value: true
    },
    isFocus: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    value: '',
    timer: null
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 输入变化
    searchChangeHandle(e) {
      clearTimeout(this.data.timer)
      this.setData({
        timer: setTimeout(() => {
          this.setData({
            value: e.detail
          })
          this.getSearchResult()
        }, 500)
      })
    },
    // 点击转跳搜索页
    searchTapHandle() {
      // 获取当前页面路径
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1].__route__
      if (currentPage.search('search') !== -1) return
      wx.navigateTo({
        url: '/pages/search/search',
      })
    },
    // 获取搜索结果
    async getSearchResult() {
      if(!this.data.value) {
        this.setData({
          searchResult: []
        })
        return
      }
      // 发起请求
      const { data: result } = await http.get('/goods/qsearch', { query: this.data.value })
      if(result.meta.status !== 200) return showToast()
      // 搜索关键词 和 搜索结果发送给页面
      this.triggerEvent('sendSearchResult', {
        searchResult: result.message, 
        keyword: this.data.value
      })
      // console.log(result)
    }
  }
})
